package twel.probenprophet.swing.ui.panels;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.annotation.PostConstruct;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

import org.metawidget.swing.SwingMetawidget;
import org.metawidget.swing.widgetprocessor.binding.beanutils.BeanUtilsBindingProcessor;

import twel.probenprophet.domain.event.StatusBarEvent;
import twel.probenprophet.domain.rules.checks.CheckStatisticsCalculator;
import twel.probenprophet.domain.rules.checks.SpellCheck;
import twel.probenprophet.profile.spells.SpellRepository;
import twel.probenprophet.profile.spells.xdiml2.jaxb.SpellDefinition;

public class SpellCheckPanel extends JPanel {

	private static final long serialVersionUID = 1L;

	private final Locale defaultLocale = Locale.getDefault();
	private final ResourceBundle resourceBundle = ResourceBundle.getBundle("i18n/SpellCheckPanel", defaultLocale);

	@Inject
	private Event<StatusBarEvent> event;
	@Inject
	private SpellRepository spellRepository;
	@Inject
	private CheckStatisticsCalculator calculator;

	private SpellCheck toInspect;
	private SwingMetawidget metawidget;

	@PostConstruct
	void init() {
		setLayout(new BoxLayout(this, SwingConstants.VERTICAL));

		add(createSpellSelectionComboBox());

		toInspect = new SpellCheck();
		toInspect.setSpellDefinition(spellRepository.getBundledSpells().iterator().next()); // FIXME hack

		metawidget = setUpMetawidget();
		metawidget.setToInspect(toInspect);

		add(metawidget);
	}

	private JComboBox createSpellSelectionComboBox() {
		Collection<SpellDefinition> bundledSpells = spellRepository.getBundledSpells();

		final JComboBox spellSelectionComboBox = new JComboBox(bundledSpells.toArray());
		spellSelectionComboBox.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				SpellDefinition selectedSpellDefinition = (SpellDefinition) spellSelectionComboBox.getSelectedItem();
				updateSelectedSpellDefinition(selectedSpellDefinition);
			}

		});

		return spellSelectionComboBox;
	}

	private void updateSelectedSpellDefinition(SpellDefinition selectedSpellDefinition) {
		toInspect.setSpellDefinition(selectedSpellDefinition);
		metawidget.getWidgetProcessor(BeanUtilsBindingProcessor.class).rebind(toInspect, metawidget);
	}

	private SwingMetawidget setUpMetawidget() {
		SwingMetawidget metawidget = new SwingMetawidget();

		metawidget.setConfig("metawidget/spellCheck.xml");
		metawidget.setBundle(resourceBundle);
		metawidget.addWidgetProcessor(new BeanUtilsBindingProcessor());

		return metawidget;
	}
}
